<?php
/**
 * Created by PhpStorm.
 * User: Rain
 * Date: 2020/5/16
 * Time: 13:58
 */

namespace app\admin\service\business\controllers\Access\Menu\Models;


use app\admin\service\model\BaseModel;
use app\model\AdminMenu;

class AdminMenuModel extends BaseModel
{
    /**
     * 获取列表
     *
     * @param array $where
     * @param array $field
     * @param bool $isPage
     * @param int $page
     * @return mixed
     */
    public function getList(array $where, array $field = [], bool $isPage = true, int $page = 10)
    {
        $this -> page = $page;
        $this -> isPage = $isPage;

        $query = AdminMenu::field($field ?: ['id', 'title', 'icon', 'uri', 'sort', 'parent_id', 'status', 'create_time', 'update_time']) -> order('sort desc,id asc');

        if($where) {
            // id筛选
            if(isField($where, 'id')){
                $query -> where('id', '<>', $where['id']);
            }
        }

        return $this -> all($query);
    }

    /**
     * 获取单条
     *
     * @param int $id
     * @param array $field
     * @return mixed
     */
    public function getFind(int $id, array $field = [])
    {
        $query = AdminMenu::where('id', $id)
                -> field($field ?: ['id', 'title', 'icon', 'uri', 'sort', 'parent_id', 'description'])
                -> with('roles');

        return $this -> one($query);
    }

    /**
     * 添加
     *
     * @param array $data
     * @return mixed
     */
    public function insert(array $data)
    {
        return $this -> add(AdminMenu::class, $data);
    }

    /**
     * 修改
     *
     * @param array $data
     * @param int $id
     * @return mixed
     */
    public function edit(array $data, int $id)
    {
        return $this -> update(AdminMenu::class, array_merge($data, [
            'id' => $id
        ]));
    }

    /**
     * 删除
     *
     * @param int $id
     * @return mixed
     */
    public function delete(int $id)
    {
        return $this -> del(AdminMenu::class, [ $id ]);
    }

    /**
     * 标题是否重复
     *
     * @param string $title
     * @param int $parentId
     * @param int $id
     * @return mixed
     */
    public function isUnique(string $title, int $parentId, int $id){
        $query = AdminMenu::where('id', '<>', $id)
                -> where('title', $title)
                -> where('parent_id', $parentId);

        return $this -> value($query, 'id');
    }

    /**
     * 判断是否有子菜单
     *
     * @param int $id
     * @return mixed
     */
    public function isChildRen(int $id){
        $query = AdminMenu::where('parent_id', $id);

        return $this -> value($query, 'id');
    }

    /**
     * 更新角色
     *
     * @param int $roleId
     * @param array $ids
     */
    public function updateRole(int $roleId, array $ids){
        $role = $this -> one(AdminMenu::where('id', $roleId));

        // 清空当前角色
        $role -> roles() -> detach();

        // 新增角色
        if($ids) $role -> roles() -> saveAll($ids);
    }
}
